from PySide2.QtGui import Qt
from PySide2.QtWidgets import QProgressBar, QTableWidget, QTableWidgetItem
from pandas import DataFrame

from PySide2.QtCharts import QtCharts

from public import Skt
from view.view import ComboBox

from public import PublicData
from sensor.api_sonor import get_sensor_data
from db.tb_tread import get_start_agree_df

data = PublicData()


# 搜索传感器
def search_sensor(progress: QProgressBar = None, wait_time=5):
    skt = Skt()
    senor_set = set()
    count = int(wait_time * 2)
    per_count = int(100 / count)
    for i in range(count):
        skt.send_broadcast_for_sensor()
        for search_count in range(10):
            data = get_sensor_data()
            if data:
                sensor_code = data[0]
            if sensor_code not in senor_set:
                senor_set.add(sensor_code)
        if progress:
            progress.setValue(per_count * i)
    return senor_set


# 显示传感器
def show_sensor(tb_sensor: QTableWidget):
    location_list = data.location_list
    agree_list = data.agree_list
    sensor_code_list = data.sensor_code_list
    if not sensor_code_list:
        sensor_code_list = ["no_senor"]
    if sensor_code_list:
        row_index = 0
        tb_sensor.setRowCount(len(sensor_code_list))
        for sensor_id in sensor_code_list:
            tb_sensor.setItem(row_index, 0, QTableWidgetItem(sensor_id))
            tb_sensor.setCellWidget(row_index, 1, ComboBox(location_list))
            tb_sensor.setCellWidget(row_index, 2, ComboBox(agree_list))
            row_index += 1


# 初始化传感器表
def setup_tb_sensor(tb_sensor: QTableWidget):
    col_title = ["编号", "位置", "方位", "X_角度", "Y_角度", "Z_角度", "X_加速度", "Y_加速度", "Z_加速度", "温度",
                 "电量"]
    # col_name = ["sensor_id", "location", "position", "angle_x", "angle_y", "angle_z", "acc_x", "acc_y", "acc_z",
    #             "acc_x", "bat"]
    tb_sensor.setColumnCount(len(col_title))
    tb_sensor.setHorizontalHeaderLabels(col_title)
    # show_sensor(tb_sensor)


# 获取传感器数据存到队列中
def get_sensor_data_to_queue(data):
    public_data = PublicData()
    sensor_dic = public_data.sensor_dic
    sensor_code_list = public_data.sensor_code_list

    while public_data.data_read_signal:
        data_list = []
        for i in range(5 * len(sensor_code_list)):
            data = get_sensor_data()
            if data:
                sensor_code = data[0]
                if sensor_code in sensor_dic.keys():
                    data.append(sensor_dic[sensor_code].id)
                else:
                    data.append(0)

            data_list.append(data)
        public_data.queue_sensor_data.put(data_list)


def send_sensor_data_to_queue(data):
    public_data = PublicData()
    sensor_dic = public_data.sensor_dic
    sensor_code_list = public_data.sensor_code_list
    data_list = public_data.temp_sensor_data_list
    if public_data.data_read_signal:
        if len(data_list) >= 5 * len(sensor_code_list) + 1:
            public_data.queue_sensor_data.put(data_list)
            public_data.temp_sensor_data_list = []
        if data:
            sensor_code = data[0]
            if sensor_code in sensor_dic.keys():
                data.append(sensor_dic[sensor_code].id)
            else:
                data.append(0)
            data_list.append(data)


# 处理数据线程


def check_first_record(product_id):
    """检查初始值"""
    public_data = PublicData()
    df_first_record = get_start_agree_df(product_id)
    if not df_first_record.empty:
        public_data.df_start_mean = df_first_record
        return True
    return False


def start_df_mean_to_sensor(df_start_mean: DataFrame):
    """把初始值存入传感器中"""
    if type(df_start_mean) is DataFrame:
        sensor_code_list = df_start_mean.index.to_list()
        sensor_dict = data.sensor_dic
        sensor_dict_keys = sensor_dict.keys()
        for sensor_code in sensor_code_list:
            if sensor_code in sensor_dict_keys:
                sensor_dict[sensor_code].agree_base_agree = list(
                    df_start_mean.loc[sensor_code, ["angle_x", "angle_y", "angle_z"]])


def show_bend_chart(bend_chart: QtCharts.QChart):
    # 图标框基础设置

    # x 轴
    axis_x = QtCharts.QValueAxis()  # 定义X轴
    axis_x.setLabelFormat("d%")  # 数据的表达格式
    axis_x.setTickCount(51)
    bend_chart.addAxis(axis_x, Qt.AlignBottom)

    # y 轴
    axis_y = QtCharts.QValueAxis()  # 定义X轴
    axis_y.setLabelFormat(".1f%")  # 数据的表达格式
    axis_y.setTickCount(10)
    axis_y.setTitleText("角度值")
    bend_chart.addAxis(axis_x, Qt.AlignLeft)

    sensor_dict = data.sensor_dic
    bend_data_list = data.bend_agree_list

    data_count = len(bend_data_list)

    x_range = get_x_value(data_count)
    print(x_range)

    x_step = int(x_range / 50)  # X轴刻度值的个数

    # 警戒值曲线
    ser_bend_alarm_y = QtCharts.QLineSeries()
    ser_bend_alarm_y.setName("警戒值")
    alam_value = data.agree_max
    if alam_value < 1:
        alam_value = 90
    alarm_y = [alam_value for i in range(0, x_range, x_step)]
    data_list_to_series(ser_bend_alarm_y, alarm_y, x_step)
    ser_bend_alarm_y.attachAxis(axis_x)
    ser_bend_alarm_y.attachAxis(axis_y)
    bend_chart.addSeries(ser_bend_alarm_y)

    for senor in sensor_dict.values():
        ser_data_y: QtCharts.QLineSeries = QtCharts.QLineSeries()
        ser_data_y.setName(senor.location)
        y_value = senor.agree_data_list
        data_list_to_series(ser_data_y, y_value)
        ser_data_y.attachAxis(axis_x)
        ser_data_y.attachAxis(axis_y)
        bend_chart.addSeries(ser_data_y)


def get_x_value(data_count):
    if data_count < 100:
        return 100
    data_len = len(str(data_count))
    return 10 ** (data_len)


def data_list_to_series(series: QtCharts.QLineSeries, data_list, step=1):
    x_value = 0
    points_vector = series.pointsVector()
    if points_vector:
        last_point = points_vector.at(points_vector.size() - 1)
        x_value = last_point.x()
    x_new_value = x_value + step
    for data in data_list:
        series.append(x_new_value, data)
        x_new_value += step
